<template>
  <div class="order-create">
    <div class="container">

      <createTop firstMenu="订单管理" secondMenu="订货单" title="添加/编辑"></createTop>
      <div class="search">
        <span><span class="red-icon">※ </span> 客户  </span>
        <el-select class="right-margin" clearable size="small" v-model="customer" placeholder="请选择客户" @change="selectChange">
          <el-option v-for="item in customers" :key="item.id" :label="item.nickname" :value="item.id  "></el-option>
        </el-select>
      </div>

      <el-card class="top-card" shadow="always">
        <div slot="header" class="card-title">
          <span class="left">商品清单</span>
          <el-button
          :style="{'marginLeft':'20px'}"
          size="mini"
          plain
          type="success"
          @click="add">新增</el-button>
          <el-button class="right" plain type="success" size="small" @click="checkMtar(false)">检查配料</el-button>
        </div>
           <div class="order-create-table-wrap">
              <el-table
                :data="tableData"
                style="width: 100%"
                :fit="true"
                :stripe="true"
                size="mini"
                align="center">

                <el-table-column label="操作"
                min-width="100"
                align="center">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      plain
                      type="danger"
                      @click="del(scope.$index,scope.row)">删除</el-button>
                  </template>
                </el-table-column>

                <el-table-column
                  prop="number"
                  label="商品编号"
                  min-width="100"
                  align="center">
                </el-table-column>

                <el-table-column
                  prop="goods_name"
                  label="商品名称"
                  min-width="130"
                  align="center">
                </el-table-column>

                <el-table-column
                  prop="class_name"
                  label="商品分类"
                  min-width="130"
                  align="center">
                </el-table-column>

                <el-table-column
                  prop="model"
                  label="型号"
                  min-width="120"
                  align="center">
                </el-table-column>
                
                <el-table-column 
                label="数量"
                min-width="110"
                align="center">
                  <template slot-scope="scope">
                    <el-input 
                    v-model="scope.row.inCount" 
                    placeholder="输入出库数量"
                    @blur="check(scope)"></el-input>
                  </template>
                </el-table-column>

                <el-table-column
                  prop="price"
                  label="单价(元)"
                  min-width="120"
                  align="center">
                </el-table-column>

                <el-table-column
                  prop="allPrice"
                  label="小计(元)"
                  min-width="120"
                  align="center">
                  <template slot-scope="scope">
                    <div>{{scope.row.allPrice.toFixed(3)}}</div>
                  </template>
                </el-table-column>

              </el-table>
              <div class="otherPrice">
                其他费用 : 
                <el-input 
                size="mini"
                :style="{'width':'100px'}"
                v-model="otherPrice"
                @blur= "otherPriceChange"
                placeholder="0"></el-input>
              </div>

              <div class="otherPrice">
                总费用 : {{allPrice.toFixed(3)}}
              </div>

            </div>
      </el-card>

      <el-card :style="{'margin-bottom':'20px'}" shadow="always">
        <div slot="header" class="card-title">
          <div class="left">订单信息</div>
        </div>
        <div class="content">
          <div class="se">
            <div class="content-title">制单人</div>
            <el-input :style="{'width':'350px'}" disabled v-model="username" placeholder="读取账号"></el-input>
          </div>
          <div class="se">
            <div class="content-title">订单号 </div>
            <el-input :style="{'width':'350px'}" disabled v-model="order" placeholder="自动填充"></el-input>
          </div>
        </div>

        <div class="content">
          <div class="se">
            <div class="content-title">交货日期 <span class="red-icon">※</span></div>
            <el-date-picker
              v-model="date"
              type="date"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>

          <div class="se">
            <div class="content-title">销售员</div>
            <el-input :style="{'width':'350px'}" v-model="sellName" placeholder="输入经办人姓名"></el-input>
          </div>
        </div>

        <div class="content">
          <div class="se">
            <div class="content-title">备注 </div>
            <el-input :style="{'width':'350px'}" v-model="remark" type="textarea" :rows="5" resize="none" placeholder="输入适当的备注方便管理"></el-input>
          </div>
        </div>
      </el-card>

      <el-card class="info">
        <div slot="header" class="card-title">
          <div class="left">收货信息</div>
        </div>
        <div class="item">客户名称：{{customerInfo.nickname}}</div>
        <div class="item">收货人：{{customerInfo.name}}</div>
        <div class="item">联系电话：{{customerInfo.tel}}</div>
        <div class="item" v-if="customerInfo.telephone">电话：{{customerInfo.telephone}}</div>
        <div class="item" v-if="customerInfo.fax">传真：{{customerInfo.fax}}</div>
        <div class="item">收货地址：{{customerInfo.address}}</div>
      </el-card>

      <el-card class="fapiao">
        <div slot="header" class="card-title">
          <div class="left">发票信息</div>
        </div>
        <span><span class="red-icon">※ </span></span>
        <el-select class="fapiao-select" size="small" v-model="fapiao" placeholder="选择发票">
          <el-option v-for="item in fapiaos" :key="item.value" :label="item.nicknavalue" :value="item.value"></el-option>
        </el-select>
        <div v-if="fapiao!='不开发票'" class="fapiao-content">
          <div class="item">发票抬头：{{customerInfo.invoice}}</div>
          <div class="item">发票内容：{{customerInfo.invoice_content}}</div>
          <div class="item">纳税人识别号：{{customerInfo.taxpayer_number}}</div>
          <div class="item">地址：{{customerInfo.invoice_address}}</div>
          <div class="item">电话：{{customerInfo.tel}}</div>
          <div class="item">开户名称：{{customerInfo.account_name}}</div>
          <div class="item">开户银行：{{customerInfo.bank}}</div>
          <div class="item">银行账号：{{customerInfo.account}}</div>
        </div>
      </el-card>

      <saveBtn @confirm="confirm"></saveBtn>

      <el-dialog
        v-if="showCheck"
        :title="checkTitle"
        :visible="true"
        width="30%"
        :show-close="false">
        <div class="message" v-html="checkMessage"></div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="showCheck = false">确 定</el-button>
        </span>
      </el-dialog>

      <childTable v-show="showChild" @confirm="addTable" @close="closeChild"></childTable>

    </div>
  </div>
</template>
<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
import createTop from '@/components/createTop.vue';
import saveBtn from '@/components/saveBtn.vue';
import AjaxResquest from '@/api/apiRequest';
import childTable from '@/tables/order/orderTableChild.vue';
import { Watch } from 'vue-property-decorator';
@Component({
  components: {
    createTop,
    saveBtn,
    // tableList,
    childTable
  }
})
export default class orderCreate extends Vue {
  createRes!: AjaxResquest;
  checkRes!: AjaxResquest;
  infoRes!: AjaxResquest;
  username: string = '';
  id!: string;
  date: string = '';
  sellName: string = '';
  order: string = '';
  remark: string = '';
  tableData: any = [];

  showChild: boolean = false;

  customers: any[] = [];
  customer: string = '';
  customerRes!: AjaxResquest;
  otherPrice: string = '';
  allPrice: any = 0;
  fapiao: string = '';
  fapiaos: any[] = [
    { value: '不开发票' },
    { value: '增值税普票' },
    { value: '增值税专票' }
  ];
  checkTitle: string = '';
  // 客户信息
  customerInfo: any = {};
  checkMessage: any = '';
  showCheck: boolean = false;
  mounted() {
    if (this.$route.query.edit) {
      this.id = this.$route.query.id;
      this.infoRes = new AjaxResquest('/order/orderAddUpdate');
      this.getInfo();
    }
    this.createRes = new AjaxResquest('/order/orderAddUpdateToDo');
    this.customerRes = new AjaxResquest('/order/customersList');
    this.checkRes = new AjaxResquest('/order/checkGoodsStock');
    this.getCustomer();
  }
  getInfo() {
    this.infoRes.getFunction({ orderInfoId: this.id }).then((res: any) => {
      if (res.data.code === 1) {
        let temp = res.data.data.types;
        this.customer = temp.customers_id;
        this.selectChange(this.customer);
        this.fapiao = temp.invoiceStatus;
        this.sellName = temp.sellUsername;
        this.remark = temp.remarks;
        this.date = temp.date;
        let data: any = [];
        data.length = temp.goodsList.length;
        for (let i = 0; i < data.length; i++) {
          data[i] = {};
          data[i].goods_id = temp.goodsList[i].goods_id;
          data[i].number = temp.goodsList[i].goodsNumber;
          data[i].goods_name = temp.goodsList[i].goodsName;
          data[i].class_name = temp.goodsList[i].goodsClassName;
          data[i].model = temp.goodsList[i].goodsModel;
          data[i].inCount = temp.goodsList[i].count;
          data[i].price = temp.goodsList[i].price;
          data[i].allPrice =
            parseFloat(data[i].price) * parseFloat(data[i].inCount);
          this.allPrice = temp.all_price;
          this.otherPrice = temp.other_price ? temp.other_price : '';
        }
        this.tableData = [...this.tableData, ...data];
      }
    });
  }
  otherPriceChange() {
    console.log(this.otherPrice);
    let temp: number = 0;
    this.tableData.map((i: any) => {
      if (i.allPrice) {
        temp = temp + parseFloat(i.allPrice);
      }
    });
    if (this.otherPrice) {
      this.allPrice = (temp + parseFloat(this.otherPrice))
    } else {
      this.allPrice = temp
    }
  }
  getCustomer() {
    this.customerRes.getFunction().then((res: any) => {
      this.customers = res.data.data.types;
    });
  }
  add(val: any) {
    this.showChild = true;
  }
  del(index: number, val: any) {
    this.tableData.splice(index, 1);
  }
  closeChild() {
    this.showChild = false;
  }
  addTable(val: any) {
    console.log(val);
    let s = val;
    let temp: any[] = [];
    s.map((i: any) => {
      let data = {
        number: i.numer,
        goods_name: i.goods_name,
        goods_id: i.id,
        class_name: i.class_name,
        model: i.model,
        inCount: '1',
        price: i.price,
        allPrice: ''
      };
      temp.push(data);
    });
    this.showChild = false;
    // 商品总价
    temp.map((i: any) => {
      let val: number = parseFloat(i.inCount) * parseFloat(i.price);
      i.allPrice = val
    });
    let tempt: number = 0;
    temp.map((i: any) => {
      if (i.allPrice) {
        tempt = tempt + parseFloat(i.allPrice);
      }
    });
    if (this.otherPrice) {
      this.allPrice = tempt + parseFloat(this.otherPrice);
    } else {
      this.allPrice = tempt;
    }
    this.tableData = [...this.tableData, ...temp];
  }
  check(row: any) {
    if (row.row.inCount) {
      let val: number = parseFloat(row.row.inCount) * parseFloat(row.row.price);
      this.tableData[row.$index].allPrice = val
      let temp: number = 0;
      this.tableData.map((i: any) => {
        if (i.allPrice) {
          temp = temp + parseFloat(i.allPrice);
        }
      });
      if (this.otherPrice) {
        this.allPrice = (temp + parseFloat(this.otherPrice))
      } else {
        this.allPrice = temp
      }
    }
  }
  checkMtar() {
    // 检查配料
    let temp = this.tableData;
    console.log(temp);

    if (temp.length === 0) {
      this.$message({
        message: '还没有添加配料',
        type: 'warning'
      });
      return;
    }
    let checkData: any[] = [];
    let countNull = false;
    temp.forEach((i: any) => {
      if (!i.inCount) {
        this.$message({
          message: '清单数量不能为空',
          type: 'warning'
        });
        countNull = true;
      } else {
        let data = {
          goods_id: i.goods_id,
          count: i.inCount
        };
        checkData.push(data);
      }
    });
    if (countNull) {
      return;
    }
    this.checkMessage = '';
    this.checkRes
      .getFunction({ goodsInfo: JSON.stringify(checkData) })
      .then((res: any) => {
        this.showCheck = true;
        let temp: any = res.data.data.types;
        if (Object.prototype.toString.call(temp) === '[object String]') {
          this.checkMessage = temp;
        } else if (Object.prototype.toString.call(temp) === '[object Array]') {
          this.checkTitle = '配料库存检查';
          temp.map((i: any) => {
            this.checkMessage += `配料：${
              i.format_name
            }  缺：<span class="red">${i.number}</span> . `;
          });
        }
        // this.checkMessage = this.checkMessage.split(',').join(' ;  ▌');
      });
  }
  // checkQueding() {
  //   this.confirmSecond();

  // }
  confirm(): void {
    // this.checkMtar(true);
    if (!this.customer) {
      this.$message.error('客户不能为空');
      return;
    }
    if (!this.fapiao) {
      this.$message.error('发票信息不能为空');
      return;
    }
    if (!this.date) {
      this.$message.error('交货日期不能为空');
      return;
    }
    // 检查配料
    let temp = this.tableData;
    console.log(temp);

    if (temp.length === 0) {
      this.$message({
        message: '还没有添加配料',
        type: 'error'
      });
      return;
    }
    let sTemp: any = temp.map((i: any) => {
      return {
        goods_id: i.goods_id,
        number: i.inCount
      };
    });
    sTemp = JSON.stringify(sTemp);

    let data: any = {
      goodsData: sTemp,
      remarks: this.remark,
      sellUsername: this.sellName,
      invoiceStatus: this.fapiao,
      otherPrice: this.otherPrice,
      allPrice: this.allPrice,
      customersId: this.customer,
      date: this.date
    };
    if (this.id) {
      data = { ...data, orderInfoId: this.id };
    }
    this.createRes.getFunction(data).then((res: any) => {
      if (res.data.code === 1) {
        this.$to('order');
      }
    });
  }
  confirmSecond() {}
  selectChange(val: any) {
    let temp;
    this.customers.map((i: any) => {
      if (i.id === val) {
        this.customerInfo = i;
      }
    });
  }
}
</script>
<style lang="less">
.order-create {
  padding: 15px;
  display: flex;
  flex-direction: column;
  z-index: 101;
  box-sizing: border-box;
  overflow: auto;
  .top-card {
    box-sizing: border-box;
    margin-bottom: 15px;
  }
  .el-card {
    overflow-y: auto;
  }
  .fapiao-content {
    display: flex;
    flex-direction: column;
  }
  .content {
    font-size: 16px;
    background-color: #fff;
    border-radius: 4px;
    .content-title {
      height: 30px;
      margin-top: 5px;
      line-height: 2;
      text-align: left;
    }
    .el-upload-list__item {
      width: 350px;
    }
    .el-textarea {
      margin-bottom: 10px;
    }
  }
  .card-title {
    position: relative;
    .left {
      text-align: left;
      font-weight: 600;
    }
    .right {
      position: absolute;
      right: 0px;
      top: -5px;
    }
  }
  .search {
    text-align: left;
    margin-left: 10px;
    margin-bottom: 15px;
  }
  .info {
    text-align: left;
    .item {
      height: 30px;
    }
  }
  .otherPrice {
    margin-top: 10px;
    width: 100%;
    justify-content: flex-end;
    display: flex;
    align-items: center;
  }
  .fapiao {
    text-align: left;
    margin-top: 15px;
    .item {
      height: 30px;
    }
    .fapiao-select {
      height: 45px;
    }
  }
  .red {
    color: red;
  }
  .message {
    // padding: 3px 0;
    line-height: 20px;
  }
}
</style>
